/**
 * 接口拦截 - 针对特定的接口进行拦截处理
 */

import mitt from "mitt"
import type { PlasmoCSConfig } from "plasmo"

import { Storage } from "@plasmohq/storage"

const emitter = mitt<Record<string, { data: any; name: string }>>()

const storage = new Storage({ copiedKeyList: ["custom_itemsArray"] })

emitter.on("mtop.relationrecommend.wirelessrecommend.recommend", async ({ data, name }) => {
  if (!data.data.itemsArray) return
  const list = (await storage.get("custom_itemsArray")) || []
  const itemsArray = data.data.itemsArray.map((item: any) => {
    const matches = item.goodsInShop[0].picUrl.match(/\/i4\/i\d+\/(\d+)\//)
    const uid = matches ? matches.at(1) : ""
    const shopUrl = `https:${item.shopUrl}`
    return { ...item, uid, shopUrl, store_name: item.shopName }
  })
  storage.set("custom_itemsArray", [...list, ...itemsArray])
})

export default emitter

export const config: PlasmoCSConfig = {
  matches: ["https://s.taobao.com/search*"],
  all_frames: true,
  run_at: "document_start"
}
